<?php
namespace app\admin\controller;
use \app\admin\controller\BaseController;
use app\admin\model\Categroy;
use app\admin\model\Featured;
use app\admin\model\CategroySpecification;
use \think\Request;

class Banner extends BaseController
{
	public function index(Featured $featured,Categroy $categroy)
	{
		$this->isLogin();
		$result = $featured->select()->toArray();
		return view('banner/index', compact('result'));
	}

    /**
     * 好货优选图片编辑
     * @param Featured $featured
     */
	public function update(Featured $featured)
	{
		$this->isLogin();
		$id = input('id');
		$firstName = input('firstName');
		$secondName = input('secondName');
		$thirdName = input('thirdName');
		$res = $featured->where('categroy_id', input('post.categroy'))->count();
		if($res == '0'){
            $files = request()->file('img');
            $info = $files->move('upload');
            if (!$info) {
                $this->error('轮播图不能为空');
            }
            $data['path'] = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
            $data['classify'] = "$firstName>$secondName>$thirdName";
            $data['categroy_id'] = input('categroy');
            $data['update_time'] = time();
            $result = $featured->where(['id' => $id])->update($data);
            if($result) {
                $this->redirect($_SERVER["HTTP_REFERER"]);
            }
            return $this->error('修改失败');
        }else{
            $files = request()->file('img');
            $info = $files->move('upload');
            if (!$info) {
                $this->error('轮播图不能为空');
            }
            $data['path'] = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
            $data['update_time'] = time();
            $result = $featured->where(['id' => $id,'categroy_id'=>input('categroy')])->update($data);
            if($result) {
                $this->redirect($_SERVER["HTTP_REFERER"]);
            }
            return $this->error('已有该分类图片，请更换分类上传图片');
        }
	}
	/**
	 * 获取分类列表
	 */
	public function getCategroy(Categroy $categroy)
	{
		$this->isLogin();
		$type = input('post.type');
		$categroy_id = input('post.categroy');

		if(!$type) {
			$result = $categroy->where(['pid' => 0, 'is_use' => 0, 'grade' => 1])->select()->toArray();
		} else if ($type == '1') {
			$result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 2])->select()->toArray();
		} else {
			$result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 3])->select()->toArray();
		}
		return json_encode($result,  JSON_UNESCAPED_UNICODE);
	}
}